package thread.demo.readWriteLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test001 {
  public static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
  public static ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
  public static ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
  
  public static void main(String[] args) throws InterruptedException {
    new Thread(() -> {
      Long startTime = System.currentTimeMillis();
      readLock.lock();
      try {
        Thread.sleep(3000);
        System.out.println(String.format("我是读锁01，花费时间是: %s", System.currentTimeMillis() - startTime));
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      } finally {
        readLock.unlock();
      }
    }).start();
    
    new Thread(() -> {
      Long startTime = System.currentTimeMillis();
      // 表示 读锁加锁
      readLock.lock();
      try {
        Thread.sleep(3000);
        System.out.println(String.format("我是读锁02，花费时间是: %s", System.currentTimeMillis() - startTime));
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      } finally {
        // 表示 读锁解锁
        readLock.unlock();
      }
    }).start();
    
    TimeUnit.MILLISECONDS.sleep(10);
    
    new Thread(() -> {
      Long startTime = System.currentTimeMillis();
      writeLock.lock();
      try {
        Thread.sleep(3000);
        System.out.println(String.format("我是写锁01，花费时间是: %s", System.currentTimeMillis() - startTime));
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      } finally {
        // 表示 写锁释放
        writeLock.unlock();
      }
    }).start();
  }
}